package ext.tianma.doc.util;

import java.io.File;
import java.rmi.RemoteException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Locale;

import org.apache.log4j.Logger;

import ext.com.iba.IBAUtil;
import ext.com.workflow.WorkflowUtil;
import ext.drawing.BorrowWorkflowUtil;
import ext.generic.erp.common.CommonPDMUtil;
import ext.tianma.bom.util.GenericUtil;
import ext.tianma.doc.forms.DrawingEmailInfoBean;
import ext.tianma.util.IbaAttributeUtil;
import ext.tianma.util.PropertiesUtil;
import ext.tianma.workflow.SubmitBomReview;
import ext.tianma.workflow.WorkItemHelper;
import wt.doc.WTDocument;
import wt.fc.ObjectReference;
import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.WTObject;
import wt.lifecycle.LifeCycleHelper;
import wt.lifecycle.State;
import wt.mail.EMailMessage;
import wt.method.MethodContext;
import wt.org.WTUser;
import wt.part.WTPart;
import wt.pom.Transaction;
import wt.pom.WTConnection;
import wt.util.WTException;
import wt.workflow.engine.WfEngineHelper;
import wt.workflow.engine.WfProcess;
import wt.workflow.engine.WfState;

/**
 * 临时图纸转正式图纸提醒（邮件通知）功能
 * 
 * @author lilin
 *
 */
public class DrawingTransferUtil {
	public static final String  DocVersion  = "cn.tianma.docVersion";//版本号
	private static Locale LOCALE = Locale.CHINA;
	public static String UNSENT = "UNSENT";// 未发送
	public static String SENT = "SENT";// 已发送
	private static final String OBSOLESCENCE = "OBSOLESCENCE";
	private static String configFilePath = "codebase" + File.separator + "ext" + File.separator + "tianma"
			+ File.separator + "cfg" + File.separator + "TianmaPro.properties";
	public static String TemporaryDrawings = "临时图纸转正式发布流程"; //临时图纸转正式发布流程
	private static Logger logger = Logger.getLogger(DrawingTransferUtil.class);

	/**
	 * 添加数据到中间表
	 * 
	 * @param self
	 * @throws WTException
	 * @throws ParseException
	 */
	public static void addDateToDrawingEmailInfo(ObjectReference self) throws WTException, ParseException {
		PropertiesUtil ut = new PropertiesUtil(configFilePath);
		String transferMonth = ut.getValueByKey("drawing.transferMonth");
		int transferMonthInt = 3;// 默认为3个月
		if (transferMonth != null && !"".equals(transferMonth)) {// 配置文件中如果不为空的话，则获取配置文件中的数据
			transferMonthInt = Integer.parseInt(transferMonth);
		}
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		WfProcess process = WorkflowUtil.getProcess(self);// BomWorkFlowUtil.getProcess(self);// 获取流程
		WTObject wtObject = WorkItemHelper.getPBO(process); // getPBO(process);
		//String applyUser = process.getCreator().getName();
		if (wtObject != null && wtObject instanceof WTDocument) {
			WTDocument doc = (WTDocument) wtObject;
			//boolean enforce = wt.session.SessionServerHelper.manager.setAccessEnforced(false);
			WTPart part = DCCInquireStatementHelp.getPartByDoc(doc);//获得文档的说明部件
			String docNumber = doc.getNumber();
			String docId = PersistenceHelper.getObjectIdentifier((Persistable) doc).toString();
			String docName = doc.getName();
			String applyUser = doc.getCreatorName();//文档的创建者
			String isTemporaryPDF = IbaAttributeUtil.getAttributeValue(doc, "isTemporaryPDF");//受控PDF图纸是否为正式图纸
			String docVersion = "";// 版号
			String drawingType;
			try {
				drawingType = wt.type.ClientTypedUtility.getLocalizedTypeName(doc, LOCALE);//获得文档类型显示名称
				if("受控PDF图纸(暂时不用)".equals(drawingType)) {
					docVersion = IBAUtil.getIBAValue(doc,DocVersion)==null ? "": ((String) IBAUtil.getIBAValue(doc,DocVersion));//版号
					if(!"".equals(docVersion)) {
						docVersion = IBAUtil.getIBAValue(doc,DocVersion)==null ? "": ((String) IBAUtil.getIBAValue(doc,DocVersion));//版号
					}else {
						if(docNumber !=null && !"".equals(docNumber)) {//当料号不为空时，设置受控PDF图纸的版号
							docVersion = "0" + docNumber.charAt(docNumber.length() - 1);
						}
					}
				}else {
					docVersion = CommonPDMUtil.getVersion(doc);// 版号
				}
				String beginDate = simpleDateFormat.format(new Date());
				Calendar ct = Calendar.getInstance();
				ct.setTime(simpleDateFormat.parse(beginDate));
				ct.add(Calendar.MONTH, +transferMonthInt);// 设置月份
				String endDate = simpleDateFormat.format(ct.getTime());
				if (isTemporaryPDF.contains("临时图纸")) {
					Hashtable<String, String> values = new Hashtable<String, String>();
					values = addToHashtable(values, "PDFValidity", endDate);
					IBAUtil.setSoftTypeIBAValues(doc, values);
					String modulesDevelopedLand = IbaAttributeUtil.getAttributeValue(doc, "modulesDevelopedLand");//图纸研发地
					if("厦门G6".equals(modulesDevelopedLand)||"厦门G5.5".equals(modulesDevelopedLand)) {
						boolean createSuccess = createDrawingTransfer(docId, docName, docNumber, docVersion, beginDate, endDate,
								applyUser);
						if (createSuccess) {
							logger.info("创建成功");
						}
					}
				}else {
					Hashtable<String, String> values = new Hashtable<String, String>();
					values = addToHashtable(values, "PDFValidity", "长期有效");
					IBAUtil.setSoftTypeIBAValues(doc, values);
				}
			} catch (RemoteException e) {
				e.printStackTrace();
			} /*finally {
				wt.session.SessionServerHelper.manager.setAccessEnforced(enforce);
			}*/
		}
	}
	/**
	 * 增加临时图纸的图纸有效期 by sunlaichao 2020-02-24
	 * @param self
	 * @throws WTException
	 * @throws ParseException
	 */
	public static void addDateToPDFValidity(ObjectReference self,String string) throws WTException, ParseException {
		PropertiesUtil ut = new PropertiesUtil(configFilePath);
		String transferMonth = ut.getValueByKey("drawing.transferMonth");
		int transferMonthInt = 3;// 默认为3个月
		if (transferMonth != null && !"".equals(transferMonth)) {// 配置文件中如果不为空的话，则获取配置文件中的数据
			transferMonthInt = Integer.parseInt(transferMonth);
		}
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		WfProcess process = WorkflowUtil.getProcess(self);// BomWorkFlowUtil.getProcess(self);// 获取流程
		WTObject wtObject = WorkItemHelper.getPBO(process); // getPBO(process);
		//String applyUser = process.getCreator().getName();
		if (wtObject != null && wtObject instanceof WTDocument) {
			WTDocument doc = (WTDocument) wtObject;
			String docId = PersistenceHelper.getObjectIdentifier((Persistable) doc).toString();
			String docName = doc.getName();
			String docNumber = doc.getNumber();
			String applyUser = doc.getCreatorName();//文档的创建者
			String isTemporaryPDF = IbaAttributeUtil.getAttributeValue(doc, "isTemporaryPDF");//受控PDF图纸是否为正式图纸
			String PDFValidity = IbaAttributeUtil.getAttributeValue(doc, "PDFValidity");//图纸有效期
			String docVersion = CommonPDMUtil.getVersion(doc);// 图纸版本号
			try {
				if("延期".equals(string)) {
					Calendar ct = Calendar.getInstance();
					ct.setTime(simpleDateFormat.parse(PDFValidity));
					ct.add(Calendar.MONTH, +transferMonthInt);// 设置月份
					String endDate = simpleDateFormat.format(ct.getTime());
					if (isTemporaryPDF.contains("临时图纸")) {
						Hashtable<String, String> values = new Hashtable<String, String>();
						values = addToHashtable(values, "PDFValidity", endDate);
						IBAUtil.setSoftTypeIBAValues(doc, values);
						boolean updateSuccess = updateDrawingTransfer(docId, docName, docNumber, docVersion, endDate,
								applyUser,string);
						if (updateSuccess) {
							logger.info("创建成功");
						}
					}
				}else if ("废弃".equals(string)) {
					if (isTemporaryPDF.contains("临时图纸")) {
						boolean updateSuccess = updateDrawingTransfer(docId, docName, docNumber, docVersion, "",
								applyUser,string);
						if (updateSuccess) {
							logger.info("创建成功");
						}
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		
	}

	/**
	 * 给待转正式图纸发送邮件通知
	 * 
	 * @param db
	 * @return
	 */
	public static boolean sendEmailToBorrowTransfer(DrawingEmailInfoBean db) {
		try {
			String userName = db.getApplyuser();
			WTUser user = BorrowWorkflowUtil.getUserFromName(userName);
			String emailAddr = user.getEMail();// 电子邮件
			// logger.info("emailAddr======================" + emailAddr);
			// 邮件内容
			StringBuffer body = new StringBuffer();
			// URLFactory urlFactory = new URLFactory();
			String content = structureContent(db.getDrawingname(), db.getDrawingnumber(), db.getDrawingversion(), db.getDrawingenddate());// 构造主内容
			body.append(content);
			String[] emailSendTo = "".equals(emailAddr) || emailAddr == null ? null : emailAddr.split(";");// 2、why？
			// logger.info("邮件发送人======" + emailSendTo);
			EMailMessage email = EMailMessage.newEMailMessage();
			email.addEmailAddress(emailSendTo);
			// 邮件主题
			StringBuffer title = new StringBuffer();
			title.append("[" + db.getDrawingnumber() + "]临时图纸转正式图纸提醒");
			email.setSubject(title.toString());
			email.setMultipartSubtype("text/html;charset=\"UTF8\"");
			email.addPart(body.toString(), "text/html;charset=\"UTF8\"");
			email.send(false);
			return true;
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			// logger.info("lilin===========sendError");
			return false;
		}

	}

	/**
	 * 判断是否到转正式图纸时间
	 * 
	 * @return
	 */
	public static boolean isTransfer() {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<DrawingEmailInfoBean> dbs;
		try {
			dbs = getAllUnsentData();
			if (dbs.size() != 0) {
				for (int i = 0; i < dbs.size(); i++) {
					DrawingEmailInfoBean db = dbs.get(i);
					//Date currentDate = new Date();// 当前时间
					//判断图纸到期时间开始
					String nowDate = simpleDateFormat.format(new Date());
					Calendar ct = Calendar.getInstance();
					ct.setTime(simpleDateFormat.parse(nowDate));
					ct.add(Calendar.MONTH, +1);// 设置月份
					String Date = simpleDateFormat.format(ct.getTime());
					Date currentDate = simpleDateFormat.parse(Date);
					//判断图纸到期时间结束
					Date endDate = simpleDateFormat.parse(db.getDrawingenddate());// 转正式图纸时间
					if (currentDate.after(endDate)) {// 当前时间大于 转正式图纸时间
						String dccflag = db.getDccflag();
						if("Y".equals(dccflag)) {
							//判断临时图纸是否到期
							Calendar ct2 = Calendar.getInstance();
							ct.setTime(simpleDateFormat.parse(nowDate));
							String Date2 = simpleDateFormat.format(ct.getTime());
							Date date = simpleDateFormat.parse(Date2);
							if (date.after(endDate)) {
								WTDocument doc  = ext.generic.doc.DocWorkflowUtil.getWTDocumentByNumber(db.getDrawingnumber());
								State state = State.toState(OBSOLESCENCE);
								LifeCycleHelper.service.setLifeCycleState(doc, state);
								updateDrawingSentStates(db.getDrawingid());
							}
						}else {
							//更新版本,启动转正式流程 by sunlaichao
							if(updateVersion(db)) {	
								// 发送邮件
								if (sendEmailToBorrowTransfer(db)) {
									// logger.info("lilin==================updateDrawing");
									// 发送邮件后，更新数据状态为已发送
									updateDrawingSentStates(db.getDrawingid());
								}
							}
						}
					}
				}
			}
			return true;
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	/**
	 *  启动临时图纸转正式发布流程 by sunlaichao
	 * @param db
	 * @return
	 */
	private static boolean updateVersion(DrawingEmailInfoBean db) {
		try {
			WTDocument doc  = ext.generic.doc.DocWorkflowUtil.getWTDocumentByNumber(db.getDrawingnumber());
			if(doc !=null) {
				boolean flag = false;
				QueryResult qr = WfEngineHelper.service.getAssociatedProcesses(doc, WfState.OPEN_RUNNING,
						null);
				WfProcess process = null;
				while (qr.hasMoreElements()) {
					process = (WfProcess) qr.nextElement();
					if (process.getTemplate().getName().equals(TemporaryDrawings)) {
						flag = true;
						break;
					}

				}
				if (!flag) {
					SubmitBomReview.submitWorkflow(doc, TemporaryDrawings, true);
				}
				return true;
			}
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
	/**
	 * 修订临时启动新的图纸发布流程 by sunlaichao
	 * @param object
	 */
	public static void autoRevisePDF(WTObject object) {
		WTDocument doc = null;
		try {
			if (object instanceof WTDocument) {
				doc = (WTDocument)object;
				WTDocument newdoc = GenericUtil.autoReviseWTDocument(doc);//修订文档
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 根据文档信息构造邮件主内容
	 * 
	 * @param docName
	 * @param docNumber
	 * @param docVersion
	 * @param endDate 
	 * @return
	 */
	private static String structureContent(String docName, String docNumber, String docVersion, String endDate) {

		String content = "<table border = \"1\" align = \"center\">\r\n" + "	<tr align = \"center\">\r\n"
				+ "		<td>图纸编号</td>\r\n" + "		<td>图纸名称</td>\r\n" + "		<td>图纸版本</td>\r\n" + "		<td>最后有效时间</td>\r\n" + "	</tr>\r\n"
				+ "	<tr align = \"center\">\r\n" + "		<td>" + docNumber + "</td>\r\n" + "		<td>" + docName
				+ "</td>\r\n" + "		<td>" + docVersion + "</td>\r\n" + "		<td>" + endDate + "</td>\r\n" + "	</tr>\r\n"
				+ "	<tr align = \"center\">\r\n"
				+ "	  <td colspan=\"4\" ><font color=red>请将此临时图纸转成正式的发布图纸！</font></td>	\r\n" + "	</tr>\r\n"
				+ "</table>";
		return content;
	}

	/**
	 * 通过图纸id更新发送状态
	 * 
	 * @param drawingId
	 * @return
	 */
	public static boolean updateDrawingSentStates(String drawingId) {
		WTConnection wtconnection = null;
		PreparedStatement ps = null;
		Transaction trans = new Transaction();
		try {
			trans.start();
			MethodContext methodcontext = MethodContext.getContext();
			wtconnection = (WTConnection) methodcontext.getConnection();
			StringBuffer sql = new StringBuffer();
			sql.append("update TM_DRAWINGEMAILINFORMATION set drawingstates = '" + SENT + "' where drawingid='"
					+ drawingId + "'");
			// logger.info("------------sql" + sql.toString());
			ps = wtconnection.prepareStatement(sql.toString());
			ps.executeUpdate();

			ps.close();
			ps = null;
			wtconnection.release();
			wtconnection = null;
			trans.commit();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			trans.rollback();
			return false;
		} finally {
			if (wtconnection != null) {
				wtconnection.release();
			} // 4、关闭流
		}
	}

	/**
	 * 给数据库中增加数据
	 * 
	 * @param docId
	 * @param docName
	 * @param docNumber
	 * @param docVersion
	 * @param beginDate
	 * @param endDate
	 * @param applyUser
	 * @return
	 */
	public static Boolean createDrawingTransfer(String docId, String docName, String docNumber, String docVersion,
			String beginDate, String endDate, String applyUser) {
		WTConnection wtconnection = null;
		PreparedStatement ps = null;
		Transaction trans = new Transaction();
		try {

			trans.start();
			MethodContext methodcontext = MethodContext.getContext();
			wtconnection = (WTConnection) methodcontext.getConnection();
			StringBuffer sql = new StringBuffer();
			sql.append(
					"insert into TM_DRAWINGEMAILINFORMATION (drawingid,drawingname,drawingnumber,drawingversion,drawingbegindate,drawingenddate,applyuser,drawingstates)");
			sql.append(" values ('" + docId + "','" + docName + "','" + docNumber + "','" + docVersion + "','"
					+ beginDate + "','" + endDate + "','" + applyUser + "','" + UNSENT + "') ");
			ps = wtconnection.prepareStatement(sql.toString());
			ps.executeUpdate();// rs =
			ps.close();
			ps = null;
			wtconnection.release();
			wtconnection = null;
			trans.commit();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			trans.rollback();
			return false;
		} finally {// 1、关闭
			if (wtconnection != null) {
				wtconnection.release();
			}
		}
	}
	/**
	 * 在原数据的基础上重新设置时间 by sunlaichao
	 * @param docId
	 * @param docName
	 * @param docNumber
	 * @param docVersion2
	 * @param endDate
	 * @param applyUser
	 * @param string 
	 * @return
	 */
	private static boolean updateDrawingTransfer(String docId, String docName, String docNumber, String docVersion,
			String endDate, String applyUser, String string) {
		WTConnection wtconnection = null;
		PreparedStatement ps = null;
		Transaction trans = new Transaction();
		try {

			trans.start();
			MethodContext methodcontext = MethodContext.getContext();
			wtconnection = (WTConnection) methodcontext.getConnection();
			StringBuffer sql = new StringBuffer();
		//	sql.append("update TM_DRAWINGEMAILINFORMATION set drawingenddate = "+endDate+",drawingstates=UNSENT"+"where drawingid ="+docId);
			if("延期".equals(string)) {
				sql.append("update TM_DRAWINGEMAILINFORMATION set drawingenddate='" + endDate + "',drawingstates = '" + UNSENT + "' where DRAWINGNUMBER='"
						+ docNumber + "'");
			}else if("废弃".equals(string)) {
				sql.append("update TM_DRAWINGEMAILINFORMATION set dccflag = 'Y',drawingstates = '" + UNSENT + "' where DRAWINGNUMBER='"
						+ docNumber + "'");
			}			
			ps = wtconnection.prepareStatement(sql.toString());
			ps.executeUpdate();// rs =
			ps.close();
			ps = null;
			wtconnection.release();
			wtconnection = null;
			trans.commit();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			trans.rollback();
			return false;
		} finally {// 1、关闭
			if (wtconnection != null) {
				wtconnection.release();
			}
		}
	}

	/**
	 * 查询所有的未发送邮件的数据
	 * 
	 * @return
	 * @throws WTException
	 */
	public static List<DrawingEmailInfoBean> getAllUnsentData() throws WTException {
		WTConnection wtconnection = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		List<DrawingEmailInfoBean> list = new ArrayList<DrawingEmailInfoBean>();
		try {
			MethodContext methodcontext = MethodContext.getContext();
			wtconnection = (WTConnection) methodcontext.getConnection();
			StringBuffer sql = new StringBuffer();
			sql.append("select *");
			sql.append(" from TM_DRAWINGEMAILINFORMATION");
			sql.append(" where drawingstates ='" + UNSENT + "' ");
			// logger.info("sql=====================" + sql.toString());
			ps = wtconnection.prepareStatement(sql.toString());
			rs = ps.executeQuery();
			while (rs.next()) {
				DrawingEmailInfoBean db = new DrawingEmailInfoBean();
				db.setId(rs.getString("ID"));
				db.setDrawingid(rs.getString("drawingid"));
				db.setDrawingname(rs.getString("drawingname"));
				db.setDrawingnumber((rs.getString("drawingnumber")==null || "".equals(rs.getString("drawingnumber"))) ? "": rs.getString("drawingnumber"));
				db.setDrawingversion(rs.getString("drawingversion"));
				db.setDrawingstates(rs.getString("drawingstates"));
				db.setDccflag(rs.getString("dccflag"));
				db.setApplyuser(rs.getString("applyuser"));
				db.setDrawingbegindate(rs.getString("drawingbegindate"));
				db.setDrawingenddate(rs.getString("drawingenddate"));
				list.add(db);
			}
			rs.close();
			ps.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (wtconnection != null) {
				wtconnection.release();
			}
		}
		return list;
	}
	/**
	 * 实现Hashtable添加数据时不会出现空指针异常
	 * 
	 * @param hashtable
	 * @param key
	 * @param value
	 * @return
	 */
	private static Hashtable<String, String> addToHashtable(Hashtable<String, String> hashtable, String key,
			String value) {
		if (key == null && hashtable != null) {
			return hashtable;
		}

		if (value == null && hashtable != null) {
			return hashtable;
		}

		if (key == null && hashtable == null) {
			return new Hashtable<String, String>();
		}

		if (value == null && hashtable == null) {
			return new Hashtable<String, String>();
		}

		if (hashtable == null) {
			hashtable = new Hashtable<String, String>();
		}
		hashtable.put(key, value);

		return hashtable;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
